package com.manager.controller;

import com.manager.bean.Account;
import com.manager.bean.Student;
import com.manager.service.AccountService;
import com.manager.service.StudentService;
import com.manager.util.MD5Utils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

import com.manager.bean.PageInfo;

/**
 * (Student)表控制层
 *
 * @author makejava
 * @since 2021-03-02 20:15:30
 */
@Controller
public class StudentController {
    /* * 服务对象

     * */
    @Resource
    private StudentService studentService;

    @Resource
    private AccountService accountService;

    @RequestMapping(value = "/findStudent")
    public String findStudent(String Name, Integer StudentId,Integer ClassId, String CollegeName,
                              Integer pageIndex, Integer pageSize, Model model) {
        PageInfo<Student> pi = studentService.findPageInfo(Name,StudentId,ClassId,CollegeName,
                pageIndex,pageSize);
        model.addAttribute("pi", pi);
        return "student_list";
    }


    @RequestMapping(value = "/exportstudentlist", method = RequestMethod.POST)
    @ResponseBody
    public List<Student> exportStudent() {
        List<Student> studentList = studentService.getAll();
        return studentList;
    }


    @RequestMapping("/deleteStudent")
    @ResponseBody
    public String deleteStudent(Integer Id) {
        accountService.deleteById(Id);
        studentService.deleteById(Id);
        return "student_list";
    }


    @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
    @ResponseBody
    public String addStudent(@RequestBody Student student) {
        Account account = new Account();
        account.setAccount(student.getId());
        account.setIdentity("student");
        String salt = MD5Utils.getSalt();
        String password = MD5Utils.md5("123456"+salt);
        account.setSalt(salt);
        account.setPassword(password);
        accountService.insert(account);
        studentService.insert(student);
        return "student_list";
    }


    @RequestMapping(value = "/updateStudent", method = RequestMethod.POST)
    public String updateStudent(Student student,HttpSession session) {
        studentService.update(student);
        if(session.getAttribute("identity").equals("student")){
            return "redirect:/";
        }
        return "redirect:/findStudent";
    }


    @RequestMapping("/findStudentById")
    public String findStudentById(Integer Id, HttpSession session, Model model) {
        Student s = studentService.queryById(Id);
        session.setAttribute("s", s);
        model.addAttribute("s", s);
        return "student_edit";
    }

}
